package com.boruan.qq.zxgylibrary.service.manager;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.constants.MyApplication;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 崔琦 on 2019/5/30.
 * des: ....
 */

public class RetrofitHelper {
    private Context mContext;
    /*OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();*/
    OkHttpClient client = new OkHttpClient();
    GsonConverterFactory factory = GsonConverterFactory.create(new GsonBuilder().create());
    //使用单例模式
    private static RetrofitHelper instance = null;
    private Retrofit mRetrofit = null;
    public static RetrofitHelper getInstance(Context context){
        if (instance == null){
            instance = new RetrofitHelper(context);
        }
        return instance;
    }

    public RetrofitHelper(Context mContext) {
        this.mContext = mContext;
        init();
    }

    private void init(){
        resetApp();
    }

    private void resetApp(){
        mRetrofit = new Retrofit.Builder()
                .baseUrl(ConstantInfo.baseInterfaceUrl)
                .client(okHttpClient)
                .addConverterFactory(factory)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public RetrofitService getService(){
        return mRetrofit.create(RetrofitService.class);
    }

    private HashSet<String> tokens = new HashSet<>();
    public class ReceivedTokenInterceptor implements Interceptor {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response originalResponse = null;
            try {
                originalResponse = chain.proceed(chain.request());

                if (!originalResponse.headers("Authorization").isEmpty()) {
                    tokens.clear();
                    for (String header : originalResponse.headers("Authorization")) {
                        tokens.add(header);
                    }
                    SharedPreferences sharedPreferences = MyApplication.getSharedreferences();
                    String localToken = sharedPreferences.getString("token_test", "");
                    if ("".equals(localToken)){
                        for (String token : tokens) {
                            SharedPreferences.Editor editor = MyApplication.getSharedreferences().edit();
                            editor.putString("token_test",token);
                            editor.commit();
                            Log.i("OkHttpUrl", "Adding Header: " + token); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
                        }
                    }

                }
            }catch (UnknownHostException e){
                e.printStackTrace();
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "网络未连接，请检查你的网络设置！", Toast.LENGTH_SHORT).show();
                    }
                });

            }catch (SocketTimeoutException e){
                e.printStackTrace();
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "网络速度较慢，请换个网络重新请求，或稍后重试！", Toast.LENGTH_SHORT).show();
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
                Log.i("errorRet",e.getMessage());
            }

            return originalResponse;
        }
    }

    public class AddTokenInterceptor implements Interceptor {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            SharedPreferences sharedPreferences = MyApplication.getSharedreferences();
            String localToken = sharedPreferences.getString("token_test", "");
            if (!"".equals(localToken)){
//                builder.addHeader("Authorization", localToken);
//                Log.i("OkHttpLoca", "Adding Header: " + localToken);
            }
            return chain.proceed(builder.build());
        }
    }

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new ReceivedTokenInterceptor())
            .addInterceptor(new AddTokenInterceptor())
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS).build();
}
